<?php

namespace App\Admin\Controllers;

use App\Admin\Forms\ReceiptStatusForm;
use App\Admin\Repositories\Receipt;
use App\Models\Order;
use App\Models\User;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Http\Request;

class ReceiptController extends AdminController
{
    public function set_status($id, Request $request)
    {
        if ($post = $request->post()) {
            $model = \App\Models\Receipt::find($id);
            $model->status = $post['status'];
            $model->express_name = $post['express_name'];
            $model->express_number = $post['express_number'];
            $model->express_img = $post['express_img'];
            $model->save();
            return Admin::json()->success('状态修改成功!')->refreshIf(true);
        }
        return Admin::json()->error('操作非法');
    }


    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Receipt(['user', 'receiptInfo']), function (Grid $grid) {
            $grid->disableViewButton();
            $grid->model()->orderBy('created_at', 'desc');
            $grid->scrollbarX();
            $grid->withBorder();
            $grid->addTableClass(['table-text-center']);

            $grid->column('id')->sortable();

            // 添加不存在的字段
            $grid->column('user.realname', '申请人');
            // $grid->column('user.nickname', '真实姓名');
            $grid->column('user.phone', '手机号');

            // $grid->column('order_sn', '订单编号');


            $grid->column('receiptInfo.header', '发票抬头');
            $grid->column('total_money');
            $grid->column('receiptInfo.type', '发票类型')->display(function ($type) {
                // dump($type);
                if (empty($type)) {
                    return '未填写发票信息';
                }
                return Receipt::getInvoiceType($type);
            })->label([
                null => 'red',
                1 => 'info',
                2 => 'success'
            ]);
            $grid->column('status', '状态')
                ->using(Receipt::getStatusOptions())
                ->badge([1 => 'success'])
                ->modal('修改发票状态', function () {
                    return ReceiptStatusForm::make()->payload(['row' => $this->toArray()]);
                });
            // $grid->column('邮寄信息')->display(function () {
            //     $express_name = Receipt::getExpressNameOptions();
            //     if (empty($this->express_name) || empty($this->express_number)) {
            //         return ' - ';
            //     } else {
            //         $express_name = isset($express_name[$this->express_name]) ? $express_name[$this->express_name] : '';
            //         return  $express_name . '/' . $this->express_number;
            //     }
            // });
            // $grid->column('express_name')->using(Receipt::getExpressNameOptions());
            // $grid->column('express_number');
            // $grid->column('express_img')->image('', 100, 100);
            $grid->column('created_at');
            // $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {

                $filter->where('search', function ($query) {
                    $query->whereHas('user', function ($query) {
                        $query->where('users.realname', 'like', "%{$this->input}%")
                            ->orWhere('users.nickname', 'like', "%{$this->input}%")
                            ->orWhere('users.phone', 'like', "%{$this->input}%");
                    });
                }, '申请人/昵称/手机号');

                $filter->equal('status', '状态')->select(Receipt::getStatusOptions());
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Receipt(), function (Show $show) {
            $show->field('id');
            $show->field('user_id');
            $show->field('order_sn');
            $show->field('type');
            $show->field('status');
            $show->field('total_money');
            $show->field('header');
            $show->field('company_addr');
            $show->field('company_phone');
            $show->field('bank_name');
            $show->field('bank_number');
            $show->field('tax_user_id');
            $show->field('tax_cert');
            $show->field('receive_user');
            $show->field('receive_mobile');
            $show->field('receive_addr');
            $show->field('remark');
            $show->field('express_name');
            $show->field('express_number');
            $show->field('express_img')->file();
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Receipt(), function (Form $form) {
            $form->disableViewButton();
            $form->disableViewCheck();
            $form->select('user_id', '申请人')->options(User::where(['status' => 1])->pluck('username', 'id'))->disable();
            $form->textarea('order_id', '订单编号')->customFormat(function ($order_sn) {
                $order = Order::find(explode(',', $order_sn))->pluck('order_sn')->toArray();
                if (!empty($order)) {
                    return implode(' | ', $order);
                } else {
                    return '';
                }
            })->disable();
            $form->select('type')->options(Receipt::getInvoiceType());
            $form->radio('status', '邮寄状态')->options(Receipt::getStatusOptions())
                ->when(1, function (Form $form) {
                    $form->file('receipt_file', '电子发票')->saveFullUrl()->autoUpload()->move('receipt/' . date('Y/m') . '/' . uniqid())->rules('required_if:status,1', ['required_if' => '请填写完整该项'])->saving(function ($path) {
                        return httpToHttps($path);
                    });;
                });
            $form->text('total_money');
            $form->text('header')->readOnly();
            $form->select('tax_type', '公司信息区别')->options([1 => '纳税人识别号', 2 => '统一社会信用代码'])->required()->disable();
            $form->text('tax_user_id')->readOnly();
            $form->file('tax_cert')->autoUpload()->move('receipt/' . date('Y/m') . '/' . uniqid())->saveFullUrl();
            // $form->text('receive_user');
            // $form->text('receive_mobile');
            // $form->text('receive_addr');
            $form->textarea('remark');


            $form->ignore(['order_sn']);
            $form->display('created_at');
            $form->display('updated_at');
        });
    }
}
